<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blogs/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Node.js," />










<meta name="description" content="Express代码优化（MyServer）1.封装错误代码块在所有路由之前，封装一个经常用到的错误的模板中间件 123456789101112&#x2F;&#x2F; 响应错误的模板中间件app.use((req,res,next)&#x3D;&gt;&amp;#123;  &#x2F;&#x2F; status默认值为1,表示失败  &#x2F;&#x2F; err是一个错误的对象  res.cc &#x3D; function(err,status &#x3D; 1)&amp;#123;    r">
<meta property="og:type" content="article">
<meta property="og:title" content="Express代码优化">
<meta property="og:url" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/index.html">
<meta property="og:site_name" content="Chao&#39;s blog">
<meta property="og:description" content="Express代码优化（MyServer）1.封装错误代码块在所有路由之前，封装一个经常用到的错误的模板中间件 123456789101112&#x2F;&#x2F; 响应错误的模板中间件app.use((req,res,next)&#x3D;&gt;&amp;#123;  &#x2F;&#x2F; status默认值为1,表示失败  &#x2F;&#x2F; err是一个错误的对象  res.cc &#x3D; function(err,status &#x3D; 1)&amp;#123;    r">
<meta property="og:locale">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic1.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic2.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic3.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic4.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic5.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic6.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic7.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic8.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic9.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic10.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic11.png">
<meta property="article:published_time" content="2022-05-01T06:31:32.000Z">
<meta property="article:modified_time" content="2022-05-01T14:03:47.928Z">
<meta property="article:author" content="Chaoyxy">
<meta property="article:tag" content="Node.js">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://louchaoyy.gitee.io/blogs/2022/05/01/Express代码优化/"/>





  <title>Express代码优化 | Chao's blog</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chao's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blogs/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://louchaoyy.gitee.io/blogs/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogs/images/cat.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chao's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Express代码优化</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-05-01T14:31:32+08:00">
                2022-05-01
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2022/05/01/Express代码优化/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Express代码优化（MyServer）"><a href="#Express代码优化（MyServer）" class="headerlink" title="Express代码优化（MyServer）"></a>Express代码优化（MyServer）</h1><h2 id="1-封装错误代码块"><a href="#1-封装错误代码块" class="headerlink" title="1.封装错误代码块"></a>1.封装错误代码块</h2><p>在所有路由之前，封装一个经常用到的错误的模板中间件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 响应错误的模板中间件</span></span><br><span class="line">app.use(<span class="function">(<span class="params">req,res,next</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="comment">// status默认值为1,表示失败</span></span><br><span class="line">  <span class="comment">// err是一个错误的对象</span></span><br><span class="line">  res.cc = <span class="function"><span class="keyword">function</span>(<span class="params">err,status = <span class="number">1</span></span>)</span>&#123;</span><br><span class="line">    res.send(&#123;</span><br><span class="line">      <span class="attr">status</span>:status,</span><br><span class="line">      <span class="attr">msg</span>:err <span class="keyword">instanceof</span> <span class="built_in">Error</span> ? err.message : err,</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;;</span><br><span class="line">  next();</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>需要调用到的地方，直接使用req.cc()传入两个参数即可。</p>
<p>如下，假如在<code>/users/hello</code>这个接口中使用到req.cc，则</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// hello接口</span></span><br><span class="line">router.get(<span class="string">&#x27;/hello&#x27;</span>,<span class="function">(<span class="params">req,res</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="keyword">typeof</span>(req.query))</span><br><span class="line">  <span class="keyword">if</span>(<span class="built_in">JSON</span>.stringify(req.query)==<span class="string">&quot;&#123;&#125;&quot;</span>)&#123;</span><br><span class="line">    <span class="keyword">return</span> res.cc(<span class="string">&quot;无参数&quot;</span>,<span class="number">1</span>);</span><br><span class="line">  &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">    res.send(&#123;</span><br><span class="line">    <span class="attr">status</span>:<span class="number">200</span>,</span><br><span class="line">    <span class="attr">msg</span>:req.query,</span><br><span class="line">  &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<span id="more"></span>

<p>使用postman进行成功和错误的请求为：</p>
<img src="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic1.png" class title="成功的请求">

<p>失败的请求如下：</p>
<img src="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic2.png" class title="错误的请求">

<h2 id="2-加密"><a href="#2-加密" class="headerlink" title="2.加密"></a>2.加密</h2><p>使用bcryptjs模块对密码进行加密</p>
<p>安装</p>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install bcryptjs -<span class="literal">-save</span></span><br></pre></td></tr></table></figure>

<p>使用bcrptjs里面的hashsync()方法对一个字符串进行加密</p>
<p>在本例中，我在注册中间件的时候进行加密</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//中间件函数 middleware.js</span></span><br><span class="line"><span class="comment">// 引入bcryptjs包</span></span><br><span class="line"><span class="keyword">const</span> bcrypt = <span class="built_in">require</span>(<span class="string">&#x27;bcryptjs&#x27;</span>);</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * middleUers.js</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>req  请求对象</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>res  响应对象</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>next 下一步执行回调函数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="built_in">exports</span>.mw1 = <span class="function">(<span class="params">req,res,next</span>)=&gt;</span>&#123;</span><br><span class="line">    req.body.reach = <span class="literal">true</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;我是第1个中间件,我添加了一个reach的属性&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span>.mw2 = <span class="function">(<span class="params">req,res,next</span>)=&gt;</span>&#123;</span><br><span class="line">    req.body.islogin = <span class="literal">true</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;我是第2个中间件,我添加了一个islogin的属性&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 给注册接口新增一个删除为0的标志位</span></span><br><span class="line"><span class="built_in">exports</span>.registerDeleted = <span class="function">(<span class="params">req,res,next</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="comment">// 给注册接口新增一个删除为0的标志位</span></span><br><span class="line">    req.body.isdeleted = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">// 使用bcryptjs 对用户密码进行加密</span></span><br><span class="line">    req.body.password = bcrypt.hashSync(req.body.password);</span><br><span class="line">    next();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在路由处理函数中，此时password已经被加密了</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//routerhanler.js</span></span><br><span class="line"><span class="comment">// 把用户名和密码插入数据库</span></span><br><span class="line"><span class="built_in">exports</span>.registerUser = <span class="function">(<span class="params">req,res</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">const</span> info = req.body;</span><br><span class="line">    <span class="built_in">console</span>.log(req.body.psaaword); <span class="comment">//$2a$10$BJ1ymod2qUxr2Cxkg9G3AOLDih4TUmm3SppaSv8mPmYEATEQUTO7G</span></span><br><span class="line">    <span class="keyword">const</span> sqlstr = <span class="string">&#x27;INSERT INTO sy_users SET ? &#x27;</span>;</span><br><span class="line">    db.query(sqlstr,info,<span class="function">(<span class="params">err,result</span>)=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (result.affectedRows!==<span class="number">1</span>) &#123;</span><br><span class="line">           <span class="keyword">return</span> res.cc(err,<span class="number">1</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            res.send(&#123;</span><br><span class="line">                <span class="attr">status</span>:<span class="number">200</span>,</span><br><span class="line">                <span class="attr">msg</span>:<span class="string">&quot;注册成功！&quot;</span></span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>表中如下：</p>
<img src="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic3.png" class title="admin1的密码为加密字符串">

<h2 id="3-登录"><a href="#3-登录" class="headerlink" title="3.登录"></a>3.登录</h2><p>在第二步中，我们得到一个加密字符串，此时如果想要使用该字符串来直接进行===比较，肯定是失败的，因为被加密过了 ，因此我们需要使用bcryptjs中的compareSync()方法进行比较，返回值是一个bool值，如果true就成功，反之则失败了</p>
<p><strong>compareSync(str1,str2)</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在路由处理函数中，对密码进行比对</span></span><br><span class="line"><span class="built_in">exports</span>.login = <span class="function">(<span class="params">req,res</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="comment">// 符合账号名且没有被删除</span></span><br><span class="line">    <span class="keyword">const</span> sqlstr = <span class="string">&#x27;SELECT * FROM sy_users WHERE username = ? AND isdeleted = ?&#x27;</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(req.body);</span><br><span class="line">    <span class="keyword">const</span> userInfo = req.body;</span><br><span class="line">    db.query(sqlstr,[req.body.username,<span class="number">0</span>],<span class="function">(<span class="params">err,result</span>)=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(err)&#123;</span><br><span class="line">            <span class="keyword">return</span> res.cc(err);</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span>(result.length==<span class="number">1</span>)&#123;     <span class="comment">//判断是否找到用户名</span></span><br><span class="line">            <span class="comment">// 判断密码是否正确</span></span><br><span class="line">            <span class="keyword">const</span> compareRes =bcrypt.compareSync(req.body.password,result[<span class="number">0</span>].password);</span><br><span class="line">            <span class="keyword">if</span> (compareRes) &#123;</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">&quot;登录成功！&quot;</span>);</span><br><span class="line">                res.send(&#123;</span><br><span class="line">                    <span class="attr">status</span>:<span class="number">200</span>,</span><br><span class="line">                    <span class="attr">msg</span>:<span class="string">&quot;登录成功！&quot;</span></span><br><span class="line">                &#125;)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> res.cc(<span class="string">&quot;密码错误&quot;</span>,<span class="number">1</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> res.cc(<span class="string">&quot;用户名输入有误 ！&quot;</span>,<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>登录成功的处理：</p>
<img src="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic4.png" class title="admin1登录成功的处理">

<p>登录不成功的处理：</p>
<img src="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic5.png" class title="admin1登录失败的处理">

<h2 id="3-生成JWT的token字符串"><a href="#3-生成JWT的token字符串" class="headerlink" title="3.生成JWT的token字符串"></a>3.生成JWT的token字符串</h2><p><strong>注意点，在生成token字符串的时候，要剔除密码和头像的值</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在ES6中，有一个展开运算符，可以将一个可迭代的对象展开，并把值给拿出来</span></span><br><span class="line"><span class="keyword">const</span> user = &#123;...result[<span class="number">0</span>],<span class="attr">password</span>:<span class="string">&#x27;&#x27;</span>&#125;;</span><br></pre></td></tr></table></figure>

<img src="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic6.png" class title="admin1在数据库中的信息被展开的结果">

<p><strong>把密码剔除掉</strong></p>
<img src="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic7.png" class title="把admin1的密码剔除掉">

<ul>
<li>安装jsonwebtoken</li>
</ul>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install jsonwebtoken -<span class="literal">-save</span></span><br></pre></td></tr></table></figure>

<p>我这里采用两个加密字符串来生成</p>
<p>通过client:myserver,password:20225520进行加密来生成，我在中间件中生成，你们可以自定义，很灵活的</p>
<p>我用base64对此进行加密，你们随意</p>
<p>安装base64包</p>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install base<span class="literal">-64</span> -<span class="literal">-save</span></span><br></pre></td></tr></table></figure>

<p><code>使用base-64编码加密</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 新建一个config文件,用于生成一个secretKey值,固定值</span></span><br><span class="line"><span class="keyword">const</span> base64 = <span class="built_in">require</span>(<span class="string">&#x27;base-64&#x27;</span>);</span><br><span class="line"><span class="comment">// 用于生成一个secretKey值,固定值</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">setSecretKey</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">const</span> secretKey = base64.encode(<span class="string">&#x27;client:myserver;password:20225520&#x27;</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;加密后的secretKey&quot;</span>,secretKey);</span><br><span class="line">    <span class="keyword">const</span> desecretKey = base64.decode(secretKey);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;解密后的secretKey&quot;</span>,desecretKey);</span><br><span class="line">   	<span class="keyword">return</span> base64.encode(<span class="string">&#x27;client:myserver;password:20225520&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="attr">jwtSecretKey</span>:setSecretKey(),</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>测试一下，结果如下：</p>
<img src="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic8.png" class title="测试一下base64加解密">

<p>在路由处理函数中，把这个值引入</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> db = <span class="built_in">require</span>(<span class="string">&#x27;../database/mysql&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> bcrypt = <span class="built_in">require</span>(<span class="string">&#x27;bcryptjs&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> config = <span class="built_in">require</span>(<span class="string">&#x27;./config&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> jwt = <span class="built_in">require</span>(<span class="string">&#x27;jsonwebtoken&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> expressJWT = <span class="built_in">require</span>(<span class="string">&#x27;express-jwt&#x27;</span>);</span><br><span class="line"><span class="comment">// 引入我们生成的secretKey</span></span><br><span class="line"><span class="keyword">const</span> secretKey = config.jwtSecretKey;</span><br></pre></td></tr></table></figure>

<p><strong>生成jwt的token给客户端响应过去</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 登录</span></span><br><span class="line"><span class="built_in">exports</span>.login = <span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 符合账号名且没有被删除</span></span><br><span class="line">    <span class="keyword">const</span> sqlstr = <span class="string">&#x27;SELECT * FROM sy_users WHERE username = ? AND isdeleted = ?&#x27;</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(req.body);</span><br><span class="line">    <span class="keyword">const</span> userInfo = req.body;</span><br><span class="line">    db.query(sqlstr, [req.body.username, <span class="number">0</span>], <span class="function">(<span class="params">err, result</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (err) &#123;</span><br><span class="line">            <span class="keyword">return</span> res.cc(err);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (result.length == <span class="number">1</span>) &#123;     <span class="comment">//判断是否找到用户名</span></span><br><span class="line">            <span class="comment">// 判断密码是否正确</span></span><br><span class="line">            <span class="keyword">const</span> compareRes = bcrypt.compareSync(userInfo.password, result[<span class="number">0</span>].password);</span><br><span class="line">            <span class="keyword">if</span> (compareRes) &#123;</span><br><span class="line">                <span class="comment">// 用空字符串把密码等敏感信息替换掉</span></span><br><span class="line">                <span class="keyword">const</span> user = &#123; ...result[<span class="number">0</span>], <span class="attr">password</span>: <span class="string">&#x27;&#x27;</span> &#125;;</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">&quot;展开得到的结果是&quot;</span>, user);</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">&quot;key&quot;</span>, secretKey);</span><br><span class="line">                <span class="comment">// 根据secretKey来生成token,和解密</span></span><br><span class="line">                <span class="keyword">const</span> token = <span class="string">&#x27;Bearer &#x27;</span> + jwt.sign(user, secretKey, &#123; <span class="attr">expiresIn</span>: <span class="string">&#x27;30min&#x27;</span> &#125;);</span><br><span class="line">                res.send(&#123;</span><br><span class="line">                    <span class="attr">status</span>: <span class="number">200</span>,</span><br><span class="line">                    <span class="attr">msg</span>: <span class="string">&quot;登录成功！&quot;</span>,</span><br><span class="line">                    <span class="attr">token</span>: token,</span><br><span class="line">                &#125;)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> res.cc(<span class="string">&quot;密码错误&quot;</span>, <span class="number">1</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> res.cc(<span class="string">&quot;用户名输入有误 ！&quot;</span>, <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic9.png" class title="登录成功并生成token">

<h2 id="4-解析token"><a href="#4-解析token" class="headerlink" title="4.解析token"></a>4.解析token</h2><p>由于上面第三节已经生成了token，那么在哪些路由模块中去使用token,哪些接口需要携带token才能访问呢？</p>
<p>我们将在这里进行配置</p>
<p>在app.js中的路由注册之前去配置。</p>
<p><strong>首先需要express-jwt这个中间件</strong></p>
<ul>
<li>安装express-jwt</li>
</ul>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install express<span class="literal">-jwt</span> -<span class="literal">-save</span></span><br></pre></td></tr></table></figure>

<p>在app.js中配置除了<code>/users</code>之外的所有接口都需要携带token才能获取数据</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//app.js</span></span><br><span class="line"><span class="keyword">const</span> &#123;expressjwt&#125; = <span class="built_in">require</span>(<span class="string">&#x27;express-jwt&#x27;</span>);</span><br><span class="line"><span class="comment">//  配置token解析的中间件</span></span><br><span class="line"><span class="comment">// expressjwt(&#123;secret:secretKey,algorithms:[&#x27;HS256&#x27;]&#125;就是用来解析token的中间件</span></span><br><span class="line"><span class="comment">// unless(&#123;path:[/^\/api\//]&#125;)用来指定哪些端口不需要访问权限</span></span><br><span class="line">app.use(expressjwt(&#123;<span class="attr">secret</span>:config.jwtSecretKey,<span class="attr">algorithms</span>:[<span class="string">&#x27;HS256&#x27;</span>]&#125;).unless(&#123;<span class="attr">path</span>:[<span class="regexp">/^\/users\//</span>]&#125;));</span><br></pre></td></tr></table></figure>

<p>截至目前app.js的全部代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> createError = <span class="built_in">require</span>(<span class="string">&#x27;http-errors&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> cookieParser = <span class="built_in">require</span>(<span class="string">&#x27;cookie-parser&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> logger = <span class="built_in">require</span>(<span class="string">&#x27;morgan&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> &#123;expressjwt&#125; = <span class="built_in">require</span>(<span class="string">&#x27;express-jwt&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> indexRouter = <span class="built_in">require</span>(<span class="string">&#x27;./routes/index&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> usersRouter = <span class="built_in">require</span>(<span class="string">&#x27;./routes/users&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> apiRouter = <span class="built_in">require</span>(<span class="string">&#x27;./routes/api&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> config = <span class="built_in">require</span>(<span class="string">&#x27;./router_handler/config&#x27;</span>);</span><br><span class="line"><span class="keyword">var</span> app = express();</span><br><span class="line"></span><br><span class="line"><span class="comment">// view engine setup</span></span><br><span class="line">app.set(<span class="string">&#x27;views&#x27;</span>, path.join(__dirname, <span class="string">&#x27;views&#x27;</span>));</span><br><span class="line">app.set(<span class="string">&#x27;view engine&#x27;</span>, <span class="string">&#x27;ejs&#x27;</span>);</span><br><span class="line"></span><br><span class="line">app.use(logger(<span class="string">&#x27;dev&#x27;</span>));</span><br><span class="line">app.use(express.json());</span><br><span class="line">app.use(express.urlencoded(&#123; <span class="attr">extended</span>: <span class="literal">false</span> &#125;));</span><br><span class="line">app.use(cookieParser());</span><br><span class="line">app.use(express.static(path.join(__dirname, <span class="string">&#x27;public&#x27;</span>)));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 响应错误的模板中间件</span></span><br><span class="line">app.use(<span class="function">(<span class="params">req,res,next</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="comment">// status默认值为1,表示失败</span></span><br><span class="line">  <span class="comment">// err是一个错误的对象</span></span><br><span class="line">  res.cc = <span class="function"><span class="keyword">function</span>(<span class="params">err,status = <span class="number">1</span></span>)</span>&#123;</span><br><span class="line">    res.send(&#123;</span><br><span class="line">      <span class="attr">status</span>:status,</span><br><span class="line">      <span class="attr">msg</span>:err <span class="keyword">instanceof</span> <span class="built_in">Error</span> ? err.message : err,</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;;</span><br><span class="line">  next();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//  配置token解析的中间件</span></span><br><span class="line">app.use(expressjwt(&#123;<span class="attr">secret</span>:config.jwtSecretKey,<span class="attr">algorithms</span>:[<span class="string">&#x27;HS256&#x27;</span>]&#125;).unless(&#123;<span class="attr">path</span>:[<span class="regexp">/^\/users\//</span>]&#125;));</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">&#x27;/&#x27;</span>, indexRouter);</span><br><span class="line">app.use(<span class="string">&#x27;/users&#x27;</span>, usersRouter);</span><br><span class="line">app.use(<span class="string">&#x27;/api&#x27;</span>,apiRouter);</span><br><span class="line"></span><br><span class="line"><span class="comment">// catch 404 and forward to error handler</span></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">req, res, next</span>) </span>&#123;</span><br><span class="line">  next(createError(<span class="number">404</span>));</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// error handler</span></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">err, req, res, next</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// set locals, only providing error in development</span></span><br><span class="line">  res.locals.message = err.message;</span><br><span class="line">  res.locals.error = req.app.get(<span class="string">&#x27;env&#x27;</span>) === <span class="string">&#x27;development&#x27;</span> ? err : &#123;&#125;;</span><br><span class="line">  <span class="keyword">if</span> (err.name === <span class="string">&#x27;UnauthorizedError&#x27;</span>) &#123;</span><br><span class="line">    res.cc(<span class="string">&quot;token认证失败&quot;</span>,<span class="number">1</span>)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// render the error page</span></span><br><span class="line">  res.status(err.status || <span class="number">500</span>);</span><br><span class="line">  res.render(<span class="string">&#x27;error&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">process.env.PORT = <span class="number">8888</span>;</span><br><span class="line"><span class="built_in">module</span>.exports = app;</span><br></pre></td></tr></table></figure>

<p><strong>测试一下</strong></p>
<p>通过postman发起一个<code>localhost:8888/api/getdata</code>不属于users的测试，本次不携带token,看看是否能成功；</p>
<img src="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic10.png" class title="不携带token的非 users请求">

<p>我们看到，由于没有携带token，所以本次请求是失败的。</p>
<p>通过postman发起一个<code>localhost:8888/api/getdata</code>不属于users的测试，本次携带token,看看是否能成功；</p>
<img src="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/pic11.png" class title="携带token的非 users 请求">

<p>我们看到，由于携带了token，所以本次请求是成功的。</p>
<p>好了，今天先到这里，代码已上传</p>
<p><a target="_blank" rel="noopener" href="https://gitee.com/louchaoyy/my-server/tree/login_and_register/">https://gitee.com/louchaoyy/my-server/tree/login_and_register/</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/alipay.jpg" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/wechatpay.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/Node-js/" rel="tag"># Node.js</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/" rel="next" title="express脚手架与路由模块化">
                <i class="fa fa-chevron-left"></i> express脚手架与路由模块化
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2022/05/02/nginx%E9%85%8D%E7%BD%AEssl%E4%B9%8B%E8%B8%A9%E5%9D%91%E7%B3%BB%E5%88%97/" rel="prev" title="nginx配置ssl之踩坑系列">
                nginx配置ssl之踩坑系列 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a target="_blank" rel="noopener" href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blogs/images/cat.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/louchaoyy" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-gitee"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="louchao@louchaoyy.cn" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96%EF%BC%88MyServer%EF%BC%89"><span class="nav-number">1.</span> <span class="nav-text">Express代码优化（MyServer）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%B0%81%E8%A3%85%E9%94%99%E8%AF%AF%E4%BB%A3%E7%A0%81%E5%9D%97"><span class="nav-number">1.1.</span> <span class="nav-text">1.封装错误代码块</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%8A%A0%E5%AF%86"><span class="nav-number">1.2.</span> <span class="nav-text">2.加密</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E7%99%BB%E5%BD%95"><span class="nav-number">1.3.</span> <span class="nav-text">3.登录</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E7%94%9F%E6%88%90JWT%E7%9A%84token%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="nav-number">1.4.</span> <span class="nav-text">3.生成JWT的token字符串</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E8%A7%A3%E6%9E%90token"><span class="nav-number">1.5.</span> <span class="nav-text">4.解析token</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chaoyxy</span>

  
</div>

<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.3</div>
-->




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/blogs/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://Chaoyxy.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'https://louchaoyy.gitee.io/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/';
          this.page.identifier = '2022/05/01/Express代码优化/';
          this.page.title = 'Express代码优化';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://Chaoyxy.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
